<template>
    <div class="courseContentChapterView">
        <template v-if="chapterId && lessonId">
            <div class="title">
                <div class="Heading">{{ chapterInfo?.displayOrder }}.{{ lessonInfo?.displayOrder }} {{ lessonInfo?.lessonName }}</div>
            </div>
            <div class="contents">
                <div class="resourceList">
                    <div class="resourceItem"
                    v-for="(resource, index) in lessonResources"
                    :class="{ selected: resource.resourceId == selectLabelResource?.resourceId }" :key="index"
                    @click="selectLabelResource = resource;">
                        <span class="iconfont" :class="{
                            'icon-likesprograma-bofangqi1': resource.resourceType == 'video',
                            'icon-likesprogramcaogaoxiang': resource.resourceType == 'resource',
                            'icon-likesprogrampinggu': resource.resourceType == 'exercise'
                        }"></span>
                        <span class="resourceName">{{ resource.resourceName }}</span>
                    </div>
                </div>
                <div class="resources">
                    <div class="resource" v-if="selectLabelResource?.resourceType == 'video'">
                        <video class="video" 
                        :src="`${baseUrl}/course/chapter/preview/video?resourceId=${selectLabelResource.resourceId}&token=${request.getToken()}`"
                        preload="metadata" controls></video>
                    </div>
                </div>
            </div>
        </template>
        <template v-else-if="hasEditingPermission && permission > 1">
            <div class="title">
                <div class="Heading">章节管理</div>
                <div class="buttons">
                    <div class="button butNormal" @click="chapterList.push({
                        chapterInfo: {
                            chapterId: 0,
                            courseId: parseSafeInt(route.params.courseId),
                            chapterName: '新章节',
                            displayOrder: chapterList.length + 1,
                            createBy: 0,
                            createDate: '',
                            updateBy: 0,
                            updateDate: ''
                        },
                        lessons: []
                    })">添加章节</div>
                    <div class="button butNormal" @click="updateViewContent">放弃编辑</div>
                    <div class="button butNormal" @click="editorChapters">保存编辑</div>
                </div>
            </div>
            <div class="contents">
                <EditorChapterList v-model="chapterList" />
            </div>
        </template>
    </div>
</template>

<script lang="ts">
import EditorChapterList from '@/components/course/EditorChapterList.vue';
import { courseApi, EditorChapter } from '@/api/course/Course';
import { Chapter, Lessons, LessonsResource } from '@/types/Course';
import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import request, { baseUrl } from '@/util/request';

export default {
    name: 'courseContentChapterView'
}
</script>

<script setup lang="ts">
    const route = useRoute();
    const chapterId = ref<number>();
    const lessonId = ref<number>();
    const hasEditingPermission = ref<boolean>(true);

    // 权限
    const permission = ref<number>(0);

    // 章节列表
    const chapterList = ref<{chapterInfo:Chapter, lessons:Lessons[]}[]>([]);

    // 章节信息
    const chapterInfo = ref<Chapter>();

    // 课时信息
    const lessonInfo = ref<Lessons>();

    const selectLabelResource = ref<LessonsResource>();

    // 课时资源
    const lessonResources = ref<LessonsResource[]>([]);

    // 参数转换函数（确保字符串转换为数字）
    const parseSafeInt = (value: string | string[] | undefined): number | undefined => {
        if (typeof value === 'string') {
            const num = parseInt(value, 10);
            return isNaN(num) ? undefined : num;
        }
        return undefined;
    };
    
    // 更新页面内容
    const updateViewContent = async () => {
        if (chapterId.value !== undefined) {
            courseApi.chapter.getChapter(chapterId.value).then(res => {
                chapterInfo.value = res.data;
            });
        }
        if (lessonId.value !== undefined) {
            courseApi.chapter.lessons.getLesson(lessonId.value).then(res => {
                lessonInfo.value = res.data;
            });
            lessonResources.value = (await courseApi.chapter.lessons.getLessonResource(lessonId.value)).data;
            selectLabelResource.value = lessonResources.value[0];
        }
        
        if (chapterId.value === undefined && lessonId.value === undefined) {// 获取章节列表
            courseApi.chapter.getList(parseSafeInt(route.params.courseId)).then(async chapterRes => {
                chapterList.value = [];
                let lessons:Lessons[] = [];
                for (const chapter of chapterRes.data) {
                    await courseApi.chapter.lessons.getList(chapter.chapterId).then(lessonRes => {
                        lessons = [];
                        for (const lesson of lessonRes.data) {
                            lessons.push(lesson);
                        }
                        chapterList.value.push({
                            chapterInfo: chapter,
                            lessons: lessons
                        });
                    });
                }
            });
        }
    };

    // 修改章节
    const editorChapters = () => {
        const updateChapterList: EditorChapter = {
            courseId: parseSafeInt(route.params.courseId), // 假设所有章节的 courseId 相同
            chapters: chapterList.value.map(({ chapterInfo, lessons }) => ({
                chapterId: chapterInfo.chapterId,
                chapterName: chapterInfo.chapterName,
                displayOrder: chapterInfo.displayOrder,
                lessons: lessons.map(lesson => ({
                    lessonsId: lesson.lessonsId,
                    lessonName: lesson.lessonName,
                    displayOrder: lesson.displayOrder
                }))
            }))
        };
        console.log(updateChapterList);
        courseApi.chapter.updateChapter(updateChapterList).then(res => {
            if (res) {
                alert('保存成功');
                updateViewContent();
            } else {
                alert('修改失败');
            }
        });
    }

    // 监听路由参数的变化
    watch(
        () => ({
            chapterIdParam: route.query.chapterId,
            lessonIdParam: route.query.lessonId,
        }),
        async ({ chapterIdParam, lessonIdParam }) => {
            // 转换并更新 chapterId
            chapterId.value = parseSafeInt(chapterIdParam);
            // 转换并更新 lessonId
            lessonId.value = parseSafeInt(lessonIdParam);
            const courseId = parseSafeInt(route.params.courseId);
            permission.value = (await courseApi.getMemberPermission(courseId));
            
            // 更新页面内容
            updateViewContent();

            selectLabelResource.value = lessonResources.value[0];
        },
        { immediate: true }
    );
</script>

<style src="@/assets/icons/iconfont.css" scoped></style>
<style scoped>
.courseContentChapterView {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

/* 标题 */
.courseContentChapterView .title {
    width: 100%;
    display: flex;
    flex-shrink: 0;
    gap: 20px;
    padding: 10px 30px;
    font-size: 16px;
    justify-content: space-between;
    align-items: center;
    background-color: rgba(255, 255, 255, 1);
    backdrop-filter: blur(2rem);
    -webkit-backdrop-filter: blur(2rem);
    -moz-backdrop-filter: blur(2rem);
    -ms-backdrop-filter: blur(2rem);
}
.courseContentChapterView .title .Heading {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.courseContentChapterView .title .buttons {
    display: flex;
    gap: 10px;
    flex-shrink: 0;
    justify-content: flex-end;
    align-items: center;
}
.courseContentChapterView .title .buttons .button {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 15px;
    padding: 5px 10px;
    border-radius: 5px;
}/* 正常按钮 */
.courseContentChapterView .title .buttons .button.butNormal {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(65, 185, 255, 1);
}
.courseContentChapterView .title .buttons .button.butNormal:hover {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(65, 185, 255, .8);
}
.courseContentChapterView .title .buttons .button.butNormal:active {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(65, 185, 255, .9);
    transition: all .1s;
}
/* 删除按钮 */
.courseContentChapterView .title .buttons .button.butDelete {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(255, 0, 0, 1);
}
.courseContentChapterView .title .buttons .button.butDelete:hover {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(255, 0, 0, .7);
}
.courseContentChapterView .title .buttons .button.butDelete:active {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(255, 0, 0, .9);
    transition: all .1s;
}
/* 失效按钮 */
.courseContentChapterView .title .buttons .button.butDisable {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(185, 185, 185, 1);
}

/* 内容 */
.courseContentChapterView .contents {
    width: 100%;
    flex: 1;
    min-height: 0px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

/* 资源列表 */
.courseContentChapterView .contents .resourceList {
    width: 100%;
    flex-shrink: 0;
    padding: 0px 30px;
    display: flex;
    gap: 10px;
    justify-content: flex-start;
    align-items: center;
    background-color: rgba(255, 255, 255, 1);
    backdrop-filter: blur(2rem);
    -webkit-backdrop-filter: blur(2rem);
    -moz-backdrop-filter: blur(2rem);
    -ms-backdrop-filter: blur(2rem);
}
/* 资源项 */
.courseContentChapterView .contents .resourceList .resourceItem {
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 0px 10px;
    padding-bottom: 2px;
    font-size: 15px;
    position: relative;
    transition: all 0.3s;
}
.courseContentChapterView .contents .resourceList .resourceItem .iconfont {
    font-size: 18px;
}
.courseContentChapterView .contents .resourceList .resourceItem::after {
    content: '';
    width: 0%;
    height: 2px;
    left: 50%;
    transform: translateX(-50%);
    bottom: 0px;
    background-color: rgba(65, 185, 255, 1);
    position: absolute;
    transition: all 0.3s;
}
.courseContentChapterView .contents .resourceList .resourceItem:hover {
    color: rgba(65, 185, 255, 1);
}
.courseContentChapterView .contents .resourceList .resourceItem:hover::after {
    width: 60%;
}
.courseContentChapterView .contents .resourceList .resourceItem.selected {
    color: rgba(65, 185, 255, 1);
}
.courseContentChapterView .contents .resourceList .resourceItem.selected::after {
    width: 60%;
}

.courseContentChapterView .contents .resources {
    width: 100%;
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}
.courseContentChapterView .contents .resources .resource {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}
.courseContentChapterView .contents .resources .resource video {
    width: 100%;
    height: 100%;
}
</style>